﻿using Abp.Domain.Services;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace AVISOutBound.SSOServer.Authorization.Members
{
    public class ABGUserRegistrationManager : DomainService
    {
        public IAbpSession AbpSession { get; set; }

        private readonly ABGUserManager _userManager;
        private readonly IPasswordHasher<Member> _passwordHasher;

        public ABGUserRegistrationManager(
            ABGUserManager userManager,
            IPasswordHasher<Member> passwordHasher)
        {
            _userManager = userManager;
            _passwordHasher = passwordHasher;

            AbpSession = NullAbpSession.Instance;
        }

        public async Task<Member> RegisterAsync(string mobile)
        {
            return await RegisterAsync(mobile, mobile, $"{mobile}@abg.com", mobile, mobile, "123qwe*", false);
        }

        public async Task<Member> RegisterAsync(string name, string surname, string emailAddress, string mobile, string userName, string plainPassword, bool isEmailConfirmed)
        {
            var user = new Member
            {
                Name = name,
                Surname = surname,
                EmailAddress = emailAddress,
                IsActive = true,
                UserName = userName,
                IsEmailConfirmed = isEmailConfirmed,
                PhoneNumber = mobile
            };

            user.SetNormalizedNames();

            user.Password = _passwordHasher.HashPassword(user, plainPassword);

            CheckErrors(await _userManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync();

            return user;
        }

        protected virtual void CheckErrors(IdentityResult identityResult)
        {
            // TODO 需要处理语言包
            identityResult.CheckErrors(LocalizationManager);
        }
    }
}
